<?php

namespace App\Services\MakeAppleTreeRecords;

use App\Models\AppleTree;
use App\Models\AppleTreesRecord;
use Carbon\Carbon;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class MakeAppleTreeRecordsRequest extends FormRequest
{
	public function rules()
	{
		return [
			'apple_tree_id' => [
				'required',
				'integer',
				'min:1',
				$this->appleTree(),
			]
		];
	}

	public function appleTree()
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$appleTree = AppleTree::find($value);

			$number = AppleTreesRecord::query()->where('apple_tree_id',$appleTree->id)->where("user_id",$this->user()->id)->where("expired_at",">",Carbon::now())->count();

			$user = $this->user();


			if (! $appleTree) {
				return $fail('苹果树不存在！');
			}elseif (big_decimal($appleTree->buy_limit)->isLessThan(big_decimal(1)->plus($number))) {
				return $fail('已超最大购买量！');
			}elseif (big_decimal($user->apples)->isLessThan($appleTree->consume_apples)) {
				return $fail('用户苹果数量不足');
			}else{

				$this->appleTree = $appleTree;
				return true;
			} 
		};
	}

	public function tree()
	{
		return $this->appleTree;
	}
}
